package com.oceanstar.service.Impl;

import com.oceanstar.Pojo.*;
import com.oceanstar.mapper.CheckInMapper;
import com.oceanstar.mapper.UserInfoMapper;
import com.oceanstar.service.ICheckInService;
import com.oceanstar.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CheckInServiceImpl implements ICheckInService {
    // 注入mapper
    private final CheckInMapper checkInMapper;
    private final UserInfoMapper userInfoMapper;
    // 构造器注入
    public CheckInServiceImpl(CheckInMapper checkInMapper, UserInfoMapper userInfoMapper) {
        this.checkInMapper = checkInMapper;
        this.userInfoMapper = userInfoMapper;
    }


    /*
    *用户签到
     */
    @Override
    public CheckInRecord getCheckInRecord(String token) {
        // 解析token获取用户ID
        Claims parsedClaims = JwtUtils.parseToken(token);
        Integer id = (Integer) parsedClaims.get("id");

        // 查询用户最新签到记录
        CheckInRecord latestRecord = checkInMapper.selectLatestCheckinByUserId(id);

        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 计算积分
        int pointsToAdd = 10;
        int continuousDays = 1; // 默认连续天数为1

        if (latestRecord != null) {
            // 检查上次签到日期
            LocalDate lastCheckinDate = latestRecord.getCheckinTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();

            if (lastCheckinDate.equals(today)) {
                // 今天已经签到过了，直接返回记录
                return latestRecord;
            } else if (lastCheckinDate.equals(today.minusDays(1))) {
                // 连续签到
                continuousDays = latestRecord.getDays() + 1;
                // 连续签到积分规则：每增加一天多1积分，最高10积分
                pointsToAdd += Math.min(continuousDays-1, 10);
            }
        }

        // 创建新的签到记录
        CheckInRecord newRecord = new CheckInRecord();
        newRecord.setId(id);
        newRecord.setCheckinTime(new Date());
        newRecord.setDays(continuousDays);
        newRecord.setPoints(pointsToAdd);

        // 插入签到记录
        checkInMapper.insertCheckinRecord(newRecord);

        // 更新用户积分
        Integer currentPoints = userInfoMapper.selectUserPointsById(id);
        if (currentPoints == null) {
            currentPoints = 0;
        }
        int newPoints = currentPoints + pointsToAdd;
        userInfoMapper.updateUserPointsById(id, newPoints);

        return newRecord;
    }

    /*
     *构建签到返回的参数
     */
    public CheckInResponseDTO buildCheckInResponseDTO(CheckInRecord checkInRecord) {
        CheckInResponseDTO response = new CheckInResponseDTO();
        response.setPoints(userInfoMapper.selectUserPointsById(checkInRecord.getId()));
        if(response.getPoints() == null) {
            response.setPoints(0);}

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        response.setToday(sdf.format(checkInRecord.getCheckinTime()));

        response.setContinuousDays(checkInRecord.getDays());
        response.setRewardPoints(checkInRecord.getPoints());
        return response;
    }

    /*
     * 查询用户最新一条签到记录
     */
    public CheckInRecord getLatestCheckInRecord(String token) {
        // 解析Token获取用户ID
        Claims parsedClaims = JwtUtils.parseToken(token);
        Integer id = (Integer) parsedClaims.get("id");

        return checkInMapper.selectLatestCheckinByUserId(id);
    }

    /*
     *构建查询总积分返回的参数
     */
    @Override
    public PointsDTO buildPointsDTO(CheckInRecord checkInRecord) {
        PointsDTO response = new PointsDTO();
        response.setPoints(userInfoMapper.selectUserPointsById(checkInRecord.getId()));
        if(response.getPoints() == null) {
            response.setPoints(0);
        }
        response.setContinuousDays(checkInRecord.getDays());
        return response;
    }

    /*
     *构建查询签到记录返回参数
     */
    @Override
    public PageInfo<SignRecord> getSignRecords(String token) {
        // 解析Token获取用户ID
        Claims parsedClaims = JwtUtils.parseToken(token);
        Integer id = (Integer) parsedClaims.get("id");

        // 查询所有签到记录（CheckInRecord列表）
        List<CheckInRecord> checkInRecords = checkInMapper.selectAllCheckinsByUserId(id);

        // 创建日期格式化器
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 转换为SignRecord列表
        List<SignRecord> signRecords = checkInRecords.stream()
                .map(record -> {
                    SignRecord signRecord = new SignRecord();
                    // 格式化日期
                    if (record.getCheckinTime() != null) {
                        signRecord.setDate(sdf.format(record.getCheckinTime()));
                    } else {
                        signRecord.setDate(null); // 或者设置为默认值
                    }
                    signRecord.setRewardPoints(record.getPoints());
                    return signRecord;
                })
                .collect(Collectors.toList());
        // 构建响应
        PageInfo<SignRecord> response = new PageInfo<>();
        response.setTotal((long) signRecords.size());
        response.setRows(signRecords);  // 设置转换后的SignRecord列表
        return response;
    }

}
